package com.after.saas.file.service;

import com.after.saas.file.constants.ModuleEnum;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @Classname CacheService
 * @Description TODO
 * @auth after
 * @since 2023/6/22 10:29
 */

@Slf4j
@Service
public class CacheService {
    private final EasyExcelService easyExcelService;
    private final Cache<String, List> CACHE = CacheBuilder.newBuilder().maximumSize(1).expireAfterWrite(1, TimeUnit.DAYS).build();

    public CacheService(EasyExcelService easyExcelService) {
        this.easyExcelService = easyExcelService;
    }


    public static class CustomCallable implements Callable<List> {
        private final EasyExcelService easyExcelService;

        public CustomCallable(EasyExcelService easyExcelService) {
            this.easyExcelService = easyExcelService;
        }

        @Override
        public List call() {
            log.info("开始获取数据...");
            return easyExcelService.read("D:\\temp\\03-字典-导入模板.xlsx", ModuleEnum.DICT_MODULE.getModuleCode());
        }
    }

    public List getAll(String key) {
        try {
            return CACHE.get(key, new CustomCallable(easyExcelService));
        } catch (ExecutionException e) {
            log.warn("缓存读取失败：{}", e.getMessage());
            return easyExcelService.read("D:\\temp\\03-字典-导入模板.xlsx", ModuleEnum.DICT_MODULE.getModuleCode());
        }
    }
}
